<template>
  <el-form :inline="true" :model="clueQuery" :rules="clueRules">
    <el-form-item label="负责人">
      <el-select
          v-model="clueQuery.ownerId"
          placeholder="请选择负责人"
          @click="loadOwner"
          style="width: 200px"
          clearable>
        <el-option
            v-for="item in ownerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="所属活动">
      <el-input v-model="clueQuery.activityName" placeholder="请输入所属活动名称" clearable />
    </el-form-item>

    <el-form-item label="姓名">
      <el-input v-model="clueQuery.fullName" placeholder="请输入姓名" clearable />
    </el-form-item>

    <el-form-item label="称呼">
      <el-select
          v-model="clueQuery.appellation"
          placeholder="请选择称呼"
          @click="loadAppellation"
          style="width: 200px"
          clearable>
        <el-option
            v-for="item in appellationOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="是否贷款">
      <el-select
          v-model="clueQuery.needLoan"
          placeholder="是否需要贷款"
          style="width: 200px"
          clearable>
        <el-option
            v-for="item in needLoanOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="意向状态">
      <el-select
          v-model="clueQuery.intentionState"
          placeholder="请选择意向状态"
          style="width: 200px"
          clearable>
        <el-option
            v-for="item in intentionStateOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="意向产品">
      <el-select
          v-model="clueQuery.intentionProduct"
          placeholder="请选择意向产品"
          style="width: 200px"
          clearable>
        <el-option
            v-for="item in productOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索状态">
      <el-select
          v-model="clueQuery.state"
          placeholder="请选择线索状态"
          @click="loadState"
          style="width: 200px"
          clearable>
        <el-option
            v-for="item in clueStateOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="线索来源">
      <el-select
          v-model="clueQuery.source"
          placeholder="请选择线索来源"
          style="width: 200px"
          clearable>
        <el-option
            v-for="item in sourceOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>



    <el-form-item>
      <el-button type="primary" @click="onSearch">搜 索</el-button>
      <el-button type="primary" plain @click="onReset">重 置</el-button>
    </el-form-item>
  </el-form>



  <el-button type="primary" class="btn" @click="addClue" v-has-permission="'clue:add'">录入线索</el-button>
  <el-button type="success" class="btn" @click="importExcel" v-has-permission="'clue:import'">导入线索（Excel）</el-button>
  <el-button type="danger" class="btn" @click="batchDelClue" v-has-permission="'clue:delete'">批量删除</el-button>

  <el-table
      :data="clueList"
      style="width: 100%"
      @selection-change="handleSelectionChange">

    <el-table-column type="selection" width="50"/>
    <el-table-column type="index" label="序号" width="65"/>
    <el-table-column property="ownerDO.name" label="负责人" width="90"/>
    <el-table-column property="activityDO.name" label="所属活动" width="90" show-overflow-tooltip/>
    <el-table-column property="startTime" label="姓名" width="90" >
      <template #default="scope" >
        <el-link type="primary" @click="view(scope.row.id)">{{ scope.row.fullName }}</el-link>
<!--        <a href="javascript:" @click="view(scope.row.id)">{{ scope.row.fullName }} </a>-->
      </template>
    </el-table-column>
    <el-table-column property="appellationDO.typeValue" label="称呼"  width="90"/>
    <el-table-column property="phone" label="手机" width="100"/>
    <el-table-column property="weixin" label="微信" width="100"/>
    <el-table-column property="needLoanDO.typeValue" label="是否贷款" show-overflow-tooltip/>
    <el-table-column property="intentionStateDO.typeValue" label="意向状态" show-overflow-tooltip/>
    <el-table-column property="intentionProductDO.name" label="意向产品" show-overflow-tooltip/>

    <el-table-column property="stateDO.typeValue" label="线索状态" >
      <template #default="scope" >
        <span style="background: lightgoldenrodyellow" v-if="scope.row.state === -1">{{scope.row.stateDO.typeValue}}</span>
        <span v-else>{{scope.row.stateDO.typeValue}}</span>
      </template>
    </el-table-column>

    <el-table-column property="sourceDO.typeValue" label="线索来源" show-overflow-tooltip/>
<!--    <el-table-column property="nextContactTime" label="下次联系时间" width="165"/>-->
    <el-table-column label="操作" width="230">
      <template #default="scope">
        <el-button type="primary" @click="view(scope.row.id)" v-has-permission="'clue:view'">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)" v-has-permission="'clue:edit'">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)" v-has-permission="'clue:delete'">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      @prev-click="toPage"
      @next-click="toPage"
      @current-change="toPage"/>

  <!--  线索导入（Excel）弹窗（对话框）-->
  <el-dialog v-model="importExcelDialogVisible" title="导入线索Excel" center width="55%"
             draggable>
    <el-upload
        ref="uploadRef"
        :http-request="uploadFile"
        :auto-upload="false">

      <template #trigger>
        <el-button type="primary">选择Excel文件</el-button>
      </template>
      仅支持后缀名为.xls或.xlsx的文件

      <template #tip>
        <div class="fileTip">
          重要提示：
          <ul>
            <li>上传仅支持后缀名为.xls或.xlsx的文件；</li>
            <li>给定Excel文件的第一行将视为字段名；</li>
            <li>请确认你的文件大小不超过50MB；</li>
            <li>日期值以文本形式保存，必须符合yyyy-MM-dd的格式；</li>
            <li>日期时间一文本形式保存，必须符合yyyy-MM-dd HH:mm:ss的格式；</li>
          </ul>
        </div>
      </template>
    </el-upload>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="importExcelDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="submitExcel">导 入</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script>
import {doDelete, doGet, doPost} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";

export default {
  name: "ClueView",

  //注入
  inject : ['reload'],

  data() {
    return {
      //线索对象，初始值是空
      clueList : [{
        ownerDO : {},
        activityDO : {},
        appellationDO : {},
        needLoanDO : {},
        intentionStateDO : {},
        intentionProductDO : {},
        stateDO : {},
        sourceDO : {},
      }],
      //分页时每页显示多少条数据
      pageSize: 0,
      //分页总共查询多少条数据
      total: 0,
      //线索导入（Excel）弹窗
      importExcelDialogVisible : false,
      //线索id的数组
      clueIdArray : [],
      //线索搜索表单对象，初始值是空
      clueQuery: {},
      //负责人下拉选项
      ownerOptions: [],
      //所属活动下拉选项
      activityOptions:[],
      //线索来源下拉选项
      sourceOptions:[],
      //称呼的下拉选项
      appellationOptions:[],
      //是否贷款下拉选项
      needLoanOptions:[],
      //意向状态的下拉选项
      intentionStateOptions:[],
      //意向产品下拉选项
      productOptions:[],
      //线索状态的下拉选项
      clueStateOptions:[],
    }
  },

  mounted() {
    this.getData(1);
    this.loadDicValue('appellation');
    this.loadDicValue('needLoan');
    this.loadDicValue('intentionState');
    this.loadDicValue('clueState');
    this.loadDicValue('source');
    this.loadDicValue('product');
  },

  methods : {

    //查询线索列表
    getData(current) {
      doGet("/api/clues", {
        current: current, //当前查询第几页
        //9个搜索条件参数
        ownerId: this.clueQuery.ownerId, //负责人id
        activityName: this.clueQuery.activityName, //活动名称
        fullName: this.clueQuery.fullName, //姓名
        appellation: this.clueQuery.appellation,//称呼
        needLoan: this.clueQuery.needLoan,//是否需要贷款
        intentionState: this.clueQuery.intentionState,//意向状态
        intentionProduct: this.clueQuery.intentionProduct,//意向产品
        state: this.clueQuery.state,//线索状态
        source: this.clueQuery.source,//线索来源
      }).then(resp => {
        if (resp.data.code === 200) {
          this.clueList = resp.data.data.list;
          this.pageSize = resp.data.data.pageSize;
          this.total = resp.data.data.total;
        }
      })
    },

    //分页函数（current是element-plus组件传过来，就是传的当前页）
    toPage(current) {
      this.getData(current);
    },

    //线索导入（Excel）
    importExcel(){
      //弹个窗
      this.importExcelDialogVisible = true;
    },

    //上传文件的请求提交
    uploadFile(param){
      let fileObj = param.file;//相当于input里取得的files
      let formData = new FormData();//new一个FormData对象
      formData.append("file", fileObj);//文件对象，前面file是参数名，后面fileObj是参数值
      doPost("/api/importExcel",formData).then(resp=>{
        if (resp.data.code === 200){
          messageTip("导入成功", "success");
          //清理一下上传的文件
          this.refs.uploadRef.clearFiles();
          //页面刷新
          this.reload();
        }else {
          messageTip("导入失败", "error");
        }
      })

    },

    //提交上传Excel文件
    submitExcel(){
      this.$refs.uploadRef.submit();
    },

    //录入线索
    addClue(){
      this.$router.push("/dashboard/clue/add");
    },

    //编辑线索
    edit(id){
      this.$router.push("/dashboard/clue/edit/" + id);
    },

    //线索详情
    view(id){
      this.$router.push("/dashboard/clue/detail/" + id);
    },

    //删除线索
    del(id) {
      messageConfirm("您确定要删除该数据吗？").then(() => {//用户点击“确定”按钮就会触发then函数
        doDelete("/api/clue/" + id, {}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("删除成功", "success");
            //页面刷新
            this.reload();
          } else {
            messageTip("删除失败，原因：" + resp.data.msg, "error");
          }
        })
      }).catch(() => {//用户点击“取消”按钮就会触发catch函数
        messageTip("取消删除", "warning");
      })
    },

    //勾选或者取消勾选时，触发该函数（已经勾选的数据会传给我们这个函数）
    handleSelectionChange(selectionDataArray) {
      this.clueIdArray = [];//清空一下之前选中的数据，只需要最后一次的选中的数据
      selectionDataArray.forEach(data=>{
        let clueId = data.id;
        this.clueIdArray.push(clueId);
      })
    },

    //批量删除线索
    batchDelClue(){
      if (this.clueIdArray.length <= 0){
        //提示一下
        messageTip("请选择要删除的数据", "warning");
        return;
      }
      messageConfirm("您确定要删除这些数据吗？").then(() => {//用户点击“确定”按钮就会触发then函数
        //原来是数组：[1,3,5,7] --> ids = "1,3,5,7";
        let ids = this.clueIdArray.join(",");
        doDelete("/api/clue", {ids: ids}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("批量删除成功", "success");
            //页面刷新
            this.reload();
          } else {
            messageTip("批量删除失败，原因：" + resp.data.msg, "error");
          }
        })
      }).catch(() => {//用户点击“取消”按钮就会触发catch函数
        messageTip("取消批量删除", "warning");
      })
    },

    //搜索
    onSearch(){
      this.getData(1);
    },

    //搜索条件重重（清空）
    onReset(){
      this.clueQuery = {};
      //页面刷新
      this.reload();
    },

    //加载负责人
    loadOwner(){
      doGet("/api/owner",{}).then(resp=>{
        if (resp.data.code === 200){
          this.ownerOptions = resp.data.data;
        }
      })
    },

    //加载所属活动
    loadActivity(){
      doGet("/api/activity/all",{}).then(resp=>{
        if (resp.data.code === 200){
          this.activityOptions = resp.data.data;
        }
      })
    },

    //加载线索来源
    loadSource(){
      doGet("/api/source/all",{}).then(resp=>{
        if (resp.data.code === 200){
          this.sourceOptions = resp.data.data;
        }
      })
    },

    //加载字典数据
    loadDicValue(typeCode) {
      doGet("/api/dicvalue/" + typeCode, {}).then(resp => {
        if (resp.data.code === 200) {
          if (typeCode === 'appellation') {
            this.appellationOptions = resp.data.data;
          } else if (typeCode === 'needLoan') {
            this.needLoanOptions = resp.data.data;
          } else if (typeCode === 'intentionState') {
            this.intentionStateOptions = resp.data.data;
          } else if (typeCode === 'clueState') {
            this.clueStateOptions = resp.data.data;
          } else if (typeCode === 'source') {
            this.sourceOptions = resp.data.data;
          } else if (typeCode === 'activity') {
            this.activityOptions = resp.data.data;
          } else if (typeCode === 'product') {
            this.productOptions = resp.data.data;
          }
        }
      })
    },


  }
}
</script>

<style scoped>
.el-table {
  margin-top: 15px;
}
.fileTip {
  padding-top: 15px;
}
.el-pagination{
  margin-top: 15px;
}
</style>